from pyqtgraph.flowchart import Node
from pyqtgraph.parametertree import Parameter, ParameterTree



from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

import os

from scipy.io import loadmat, savemat

from ...utils.ZeroMQSend import ZeroMQSender
from ...utils.ZeroMQReceive import ZeroMQReceiver

class ZeroMQNode(Node):
	"""Node for loading a .mat file of MATLAB.
	Files are selected in a simple explorer

	Output terminals:
	- title: file name
	- data: return of scipy.loadmat
	"""

	nodeName = 'ZeroMQNode'
	nodePaths = [('File',)]

	def __init__(self, name):
		super().__init__(name, terminals={'tosend':{'io':'in'}, 'received': {'io': 'out'}})

		paras_property = [
			{'name': 'changeMode', 'type': 'action'},
			{'name': 'mode', 'type': 'str','value':'close', 'readonly':True},
			{'name': 'ip to send', 'type': 'str','value':'127.0.0.1'},
			{'name': 'port', 'type': 'int','value':6666}
		]

		self.paras = Parameter.create(name='params', type='group', children=paras_property)
		self.paratree = ParameterTree()
		self.paratree.setParameters(self.paras, showTop=False)
		self.send = ZeroMQSender(ip= "127.0.0.1", port =6666)
		self.receive = ZeroMQReceiver(port= 6666)

		self.paras.param('changeMode').sigActivated.connect(self.onChangeMode)
		self.receive.messageOut.connect(self.handleWithReceivedMessage)

	def handleWithReceivedMessage(self ,message):
		self.setOutput(received=message)

	def ctrlWidget(self):
		return self.paratree



	def onChangeMode(self):
		if self.paras['mode'] == 'close':
			self.paras['mode'] = 'send'
			self.send.port = self.paras['port']
			self.send.ip = self.paras['ip to send']
			self.send.keep_running = True
			self.paras.param('ip to send').setReadonly(True)
			self.paras.param('port').setReadonly(True)

		elif self.paras['mode'] == 'send':
			self.paras['mode'] = 'receive'
			self.send.keep_running=False
			self.send.wait()
			self.paras.param('ip to send').setReadonly(True)
			self.paras.param('port').setReadonly(True)
			self.receive.keep_running =True
			self.receive.start()

		elif self.paras['mode'] == 'receive':
			self.paras['mode'] = 'close'
			self.paras.param('ip to send').setReadonly(False)
			self.paras.param('port').setReadonly(False)
			self.receive.keep_running =False
			self.receive.wait()
			self.send.keep_running=False
			self.send.wait()
			
		else :
			self.paras['mode'] = 'close'
			self.paras.param('ip to send').setReadonly(False)
			self.paras.param('port').setReadonly(False)
			self.receive.keep_running =False
			self.receive.wait()
			self.send.keep_running=False
			self.send.wait()




	def process(self, tosend, display=True):

		if self.paras['mode'] == 'send' and tosend != None:
			print(self.send.state)
			if self.send.state ==  'sending':
				self.send.keep_running=False
				self.send.wait()
			self.send.message = tosend
			self.send.start()
			return {}
		if self.paras['mode'] == 'receive':
			return {'received':self.receive.message}

	def manageThread(self):
		pass

	def saveState(self):
		state = super().saveState()
		self.paras['mode'] = 'close'
		self.paras.param('ip to send').setReadonly(False)
		self.paras.param('port').setReadonly(False)
		state['paras'] = self.paras.saveState()
		return state

	def restoreState(self, state):
		super().restoreState(state)
		self.paras.restoreState(state['paras'])

	def close(self):
		self.receive.keep_running = False
		self.receive.wait()
		self.send.keep_running = False
		self.send.wait()

	#	self.receive.quit()
	#	self.receive.wait()
		super().close()


nodelist = [ZeroMQNode]

